/**
 * @author thaodo
 *
 *
 */
package com.mfsoft.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import com.mfsoft.utilities.Config;

import android.util.Log;

//adad
public class JSONParser {
	InputStream is = null;
	JSONObject jObject = null;
	String jString = "";

	public JSONParser() {
		// TODO Auto-generated constructor stub
	}

	public JSONObject getJSONFromUrl(String url, ArrayList<NameValuePair> params) {
		// lay doi tuong json tu link url
		try {
		
			DefaultHttpClient httpClient = new DefaultHttpClient();
//			HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), Config.TIMEOUT);
//			ConnManagerParams.setTimeout(httpClient.getParams(), Config.TIMEOUT);			
			HttpPost httpPost = new HttpPost(url);
			// gui du lieu theo method post
			UrlEncodedFormEntity uEnt = new UrlEncodedFormEntity(params,
					HTTP.UTF_8);
			httpPost.setEntity(uEnt);

			HttpResponse httpResPost = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResPost.getEntity();
			is = httpEntity.getContent();

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// convert is => String
		if (is != null) {
			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is));
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				jString = sb.toString();
			} catch (Exception e) {
				Log.e("Buffer Error", "Error converting result " + e.toString());
			}
		}

		// conver String thanh json obj
		// neu ket qua tra ve bang -1 la max cua page
		if (jString.equals("-1")) {
			return null;
		} else if (!jString.equals("")) {
			try {
				jObject = new JSONObject(jString);
			} catch (JSONException e) {
				Log.e("JSON Parser", "Error parsing data " + e.toString());
			}
		}
		return jObject;

	}

}
